package com.stox.client.ui.javafx.watchlist.widget;

import java.util.Collections;
import java.util.List;

import javafx.geometry.Pos;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.util.Callback;
import javafx.util.StringConverter;

import com.stox.client.api.core.ClientFactory;
import com.stox.client.api.watchlist.WatchlistClient;
import com.stox.client.ui.javafx.core.StoxPlatform;
import com.stox.shared.model.Watchlist;
import com.stox.shared.util.StringUtil;

public class WatchlistComboBox extends ComboBox<Watchlist>{
	
	public WatchlistComboBox() {
		setVisibleRowCount(5);	// TODO should come from settings
		getEditor().setAlignment(Pos.CENTER);
		setConverter(new WatchlistConverter(this));
		setButtonCell(new WatchlistCell());
		setCellFactory(new Callback<ListView<Watchlist>, ListCell<Watchlist>>() {
			@Override
			public ListCell<Watchlist> call(ListView<Watchlist> param) {
				return new WatchlistCell();
			}
		});
		
		new Thread(){
			public void run() {
				List<Watchlist> watchlists = ClientFactory.getClient(WatchlistClient.class).findAll();
				Collections.sort(watchlists);
				StoxPlatform.runLater(new Runnable(){
					@Override
					public void run() {
						if(null != watchlists && !watchlists.isEmpty()){
							getItems().setAll(watchlists);
							getSelectionModel().select(0);
						}
					}
				});
			};
		}.start();
	}
}

class WatchlistConverter extends StringConverter<Watchlist>{
	private final ComboBox<Watchlist> comboBox;
	
	public WatchlistConverter(ComboBox<Watchlist> comboBox) {
		this.comboBox = comboBox;
	}
	
	@Override
	public String toString(Watchlist watchlist) {
		if(null != watchlist){
			return watchlist.getName();
		}else
			return null;
	}

	@Override
	public Watchlist fromString(String string) {
		if(StringUtil.hasText(string) && null != comboBox.getValue()){
			Watchlist watchlist = comboBox.getValue();
			watchlist.setName(string.trim());
			return watchlist;
		}
		return null;
	}
	
}

class WatchlistCell extends ListCell<Watchlist>{
	
	@Override
	protected void updateItem(Watchlist item, boolean empty) {
		super.updateItem(item, empty);
		if(!empty && null != item){
			setText(item.getName());
		}else{
			setText(null);
		}
	}
}